package com.zframeworks.core;

import com.zframeworks.core.bean.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class z implements ApplicationRunner {

    //所有在线用户
    public static HashMap<String, User> users;// key=userid,value=User
    public static HashMap<String, String> sessions;//key=sessionid,value=userid

    /**
     * 初始化
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();
    }


    private void init() throws Exception {
        users = new HashMap<String,User>();
        sessions = new HashMap<String,String>();
    }


    /**
     * 抛出异常
     * @param e
     * @throws Exception
     */
    public static void exception(String e) throws RuntimeException {
        throw new RuntimeException(e);
    }

    /**
     * 异常信息转字符串
     * @param e 异常对象
     * @return String
     */
    public static String exceptionToString(Exception e) {
        String result = "";
        if(e!=null && e instanceof Exception) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            result = sw.toString();
        }
        return result;
    }

    /**
     * 是否不为空
     * @return
     */
    public static boolean isNotNull(Object obj) {
        if(obj!=null && !"".equals(obj) && !"null".equals(obj) && !"NULL".equals(obj) && !"Null".equals(obj) && !"NuLL".equals(obj) && !"undefined".equals(obj) && !"UNDEFINED".equals(obj)&& !"Undefined".equals(obj)) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * 是否为空
     * @return
     */
    public static boolean isNull(Object obj) {
        if(obj==null || "".equals(obj) || "null".equals(obj) || "NULL".equals(obj) || "Null".equals(obj) || "NuLL".equals(obj) || "undefined".equals(obj) || "UNDEFINED".equals(obj) || "Undefined".equals(obj)) {
            return true;
        }else {
            return false;
        }
    }

    /**
     * Map转换层Bean，使用泛型免去了类型转换的麻烦。
     * @param <T>
     * @param map
     * @param class1
     * @return
     */
    public static <T> T MapToBean(Map map, Class<T> class1) {
        T bean = null;
        try {
            bean = class1.newInstance();
            BeanUtils.populate(bean, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }




    public static void Error(String error){
        System.out.println(error);
    }
    public static void Error(String error,Exception e){
        System.out.println(error);
    }
    public static void Log(String log){
        System.out.println(log);
    }



    public static String newZid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 创建6位短信验证码
     * @return
     */
    public static String newZcode(){
        return newNumber("","",6);
    }

    public static String newNumber(){
        return newNumber("","yyyyMMddHHmmss",6);
    }

    /**
     * 创建编号
     * @param head 标识
     * @param pattern 时间格式
     * @param digit 随机长度
     * @return
     */
    public static String newNumber(String head,String pattern,int digit){
        StringBuffer returnvalue = new StringBuffer();

        //生成头标示
        if(!"".equals(head) && head!=null){
            returnvalue.append(head);
        }
        //生成日期标示
        if(z.isNotNull(pattern)) {
            String dateInfo = FormatDate(new Date(),pattern);
            returnvalue.append(dateInfo);
        }

        //生成随机数标示
        Random random = new Random();
        String fd = "";
        for (int i = 0; i < digit; i++) {
            fd = fd + "0";
        }
        returnvalue.append(FormatNumber((random.nextInt(new BigDecimal("1"+fd).intValue())%(new BigDecimal("1"+fd).intValue()-1+1) + 1),fd));

        return returnvalue.toString();
    }

    /**
     * 日期格式化
     *
     * @param date
     * @param pattern
     *            yyyy-MM-dd yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String FormatDate(Object date, String pattern) {
        if(date!=null && date instanceof Date) {
            SimpleDateFormat dateformat1 = new SimpleDateFormat(pattern);
            return dateformat1.format(date);
        }else {
            return String.valueOf(date);
        }

    }

    /**
     * 数字格式化
     * @param Number int double long
     * @param pattern "#0.00"  格式
     * @return
     */
    public static String FormatNumber(Object Number,String pattern){
        String result = "";
        if(z.isNotNull(Number)) {
            if(z.isNotNull(Number)) {
                try {
                    BigDecimal n = new BigDecimal(String.valueOf(Number));
                    DecimalFormat df = new DecimalFormat(pattern);
                    //直接舍位，不进位
                    df.setRoundingMode(RoundingMode.DOWN);
                    result = df.format(n);
                } catch (Exception e) {
                    z.Log("格式化出错："+Number+" 格式："+pattern);
                }
            }else {
                z.Log("格式化字符串出错|pattern格式定义不可为空");
            }
        }else {
            z.Log("格式化字符串出错|字符串不可为空");
        }
        return result;
    }

    /**
     * 只要确保你的编码输入是正确的,就可以忽略掉 UnsupportedEncodingException
     */
    public static String MapToUrlParams(Map<String, String> source) throws Exception {
        Iterator<String> it = source.keySet().iterator();
        StringBuilder paramStr = new StringBuilder();
        while (it.hasNext()){
            String key = it.next();
            String value = source.get(key);
            if (isNull(value)){
                continue;
            }
            try {
                // URL 编码
                value = URLEncoder.encode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                exception("转换Map=>URL出错");
            }
            paramStr.append("&").append(key).append("=").append(value);
        }
        // 去掉第一个&
        if(isNotNull(paramStr.toString())){
            return "?"+paramStr.substring(1);
        }else{
            return "";
        }

    }


}
